package com.instalinks.android.smspostservice;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.instalinks.android.lib.AppHelper;
import com.instalinks.android.smspostservice.activity.AdminConfigActivity;
import com.instalinks.android.smspostservice.activity.HelpActivity;
import com.instalinks.android.smspostservice.activity.HomeActivity;
import com.instalinks.android.smspostservice.activity.InfoActivity;
import com.instalinks.android.smspostservice.activity.MessageComposeActivity;
import com.instalinks.android.smspostservice.activity.NotificationsActivity;
import com.instalinks.android.smspostservice.activity.ServiceActivity;
import com.instalinks.android.smspostservice.activity.UserConfigActivity;
import com.instalinks.android.smspostservice.utils.AppConfig;
import com.instalinks.android.smspostservice.utils.AppNotifications;
import com.instalinks.android.smspostservice.utils.Constants;

public abstract class AppTabBaseActivity extends Activity {
	protected AppNotifications appNotifications;
	protected AppConfig mAppCfg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		appNotifications = new AppNotifications(getApplicationContext());
		mAppCfg = new AppConfig(getApplicationContext());

		if (mAppCfg.isServiceRunning())
			appNotifications.notifyServiceRunning();
		else
			appNotifications.notifyServiceDisabled();

		checkForConfig();

		if (mAppCfg.isServerNotificationFlag() || mAppCfg.isWebSmsFlag()) {
			if (mAppCfg.isConfigExists()) {
				if (mAppCfg.getRegistrationId() == null
						|| mAppCfg.getRegistrationId().trim().length() < 10) {
					startRegistrationThread();
				}
			}
		}
	}

	private void checkForConfig() {

		if (mAppCfg.isConfigExists())
			return;

		boolean result = mAppCfg.updateConfigFromHost();
		// result = false; //for testing
		if (!result) {
			appNotifications.notifyClearAll();
			jumpToError(Constants.ERR_CONFIG_DOWNLOAD);
		}
	}

	private void jumpToError(String error) {
		Intent i = new Intent();
		i.setClassName(getApplicationContext().getPackageName(),
				ErrorActivity.class.getName());

		Bundle bundle = new Bundle();
		bundle.putString("error", error);
		i.putExtras(bundle);

		startActivity(i);
		this.finish();
	}

	private void startRegistrationThread() {

		AppTabBaseActivity.this.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				new C2DMRegistrationTask().execute();
			}
		});
	}

	private class C2DMRegistrationTask extends AsyncTask<Void, Void, Void> {

		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			String label = "Registering For Push Notifications";
			pd = ProgressDialog.show(AppTabBaseActivity.this, "", label);
		}

		@Override
		protected Void doInBackground(Void... voids) {
			mAppCfg.registerForC2dm();
			return null;
		}

		@Override
		protected void onPostExecute(Void voids) {
			pd.dismiss();
			pd.cancel();
		}
	}

	protected boolean reloadConfigFromHost() {
		boolean result = mAppCfg.updateConfigFromHost();
		return result;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.app_menu, menu);

		if (!mAppCfg.isSubscribedFlag())
			menu.removeItem(R.id.mnuService);

		if (!mAppCfg.isAdminConfigVisibleFlag()) {
			menu.removeItem(R.id.mnuAdminConfig);
			menu.removeItem(R.id.mnuMessageCompose);
		}

		if (!mAppCfg.isServerNotificationFlag() && !mAppCfg.isWebSmsFlag())
			menu.removeItem(R.id.mnuNotifications);

		if (mAppCfg.isActivatedFlag())
			menu.removeItem(R.id.mnuActivate);

		return true;
	}

	@Override
	public void onBackPressed() {
		if (!(this instanceof HomeActivity)) {
			this.finish();
			Intent i = new Intent();
			i.setClassName(getApplicationContext().getPackageName(),
					HomeActivity.class.getName());
			startActivity(i);
		}
		return;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String activityClassName = HomeActivity.class.getName();

		// Handle item selection
		switch (item.getItemId()) {
		case R.id.mnuHome:
			activityClassName = HomeActivity.class.getName();
			break;
		case R.id.mnuService:
			activityClassName = ServiceActivity.class.getName();
			break;
		case R.id.mnuNotifications:
			activityClassName = NotificationsActivity.class.getName();
			break;
		case R.id.mnuInfo:
			activityClassName = InfoActivity.class.getName();
			break;
		case R.id.mnuMessageCompose:
			if (mAppCfg.isAdminConfigVisibleFlag())
				activityClassName = MessageComposeActivity.class.getName();
			else
				activityClassName = HomeActivity.class.getName();
			break;
		case R.id.mnuHelp:
			activityClassName = HelpActivity.class.getName();
			break;
		case R.id.mnuAdminConfig:
			activityClassName = AdminConfigActivity.class.getName();
			break;
		case R.id.mnuUserConfig:
			activityClassName = UserConfigActivity.class.getName();
			break;
		case R.id.mnuExit:
			if (!mAppCfg.isServiceRunning())
				appNotifications.notifyClearAll();
			AppHelper.killApp(true);
			break;
		case R.id.mnuActivate:
			mnuActivate_Click();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

		switchActivity(activityClassName);
		return true;
	}
	
	public void switchActivity(String activityClassName) {

		this.finish();

		Intent i = new Intent();
		i.setClassName(getApplicationContext().getPackageName(),
				activityClassName);
		startActivity(i);
	}
	
	private void mnuActivate_Click(){
		new ActivateTask("Activation in progress").execute();
	}
	
	private class ActivateTask extends AsyncTask<Void, Void, Boolean> {
		ProgressDialog pd;
		String onProgressMessage = "";

		public ActivateTask(String onProgressMessage) {
			this.onProgressMessage = onProgressMessage;
		}

		@Override
		protected void onPreExecute() {
			pd = ProgressDialog.show(AppTabBaseActivity.this, "",
					onProgressMessage);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return mAppCfg.activateDevice();
		}

		@Override
		protected void onPostExecute(Boolean result) {

			pd.dismiss();
			pd.cancel();

			if (result) {
				mAppCfg.alert("Request submitted for activation");
				switchActivity(HomeActivity.class.getName());
			} else {
				mAppCfg.alert("Unable to submit request for activation. Please try again later.");
			}
		}
	}
	
	protected class SubTask extends AsyncTask<Void, Void, Boolean> {
		ProgressDialog pd;
		String onProgressMessage = "";

		public SubTask(String onProgressMessage) {
			this.onProgressMessage = onProgressMessage;
		}

		@Override
		protected void onPreExecute() {
			pd = ProgressDialog.show(AppTabBaseActivity.this, "",
					onProgressMessage);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return doBackgroundWork();
		}

		@Override
		protected void onPostExecute(Boolean result) {

			pd.dismiss();
			pd.cancel();

			if (result) {
				doOnSuccess();
			} else {
				doOnFailure();
			}
		}
	}

	protected abstract boolean doBackgroundWork();

	protected abstract void doOnSuccess();

	protected abstract void doOnFailure();

}
